package com.start.im.core.handler;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.exceptions.StartBusException;
import com.start.im.core.model.StartImConversationMsg;
import com.start.im.core.storage.IStareMsgStorage;
import com.start.ws.connect.StartConnectManager;
import com.start.ws.handler.StartBaseSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.time.LocalDateTime;

@Slf4j
public class StartImSingleMsgHandler<T extends StartImConversationMsg> implements StartBaseSocketMsgHandler<T>, IStartMsg<T>, com.start.im.core.storage.IStareMsgStorage<T> {
    protected IStareMsgStorage<T> storage;

    public StartImSingleMsgHandler(IStareMsgStorage<T> storage) {
        this.storage = storage;
    }

    @Override
    public String handlerMsgType() {
        return "StartImSingleMsg";
    }


    @Override
    public void onReceive(String startUserType, String clientType, String userId, T msg, String sendClientMsgId) {
        if (StringUtils.isEmpty(msg.getMsgContent())) {
            log.warn("消息内容不能为空: sendUserId:{} ,sendClientTYpe:{} ,msg:{}", userId, clientType, JSONObject.toJSONString(msg));
            return;
        }
        if (StringUtils.isEmpty(msg.getConversationId())) {
            log.warn("会话id不能为空: sendUserId:{} ,sendClientTYpe:{} ,msg:{}", userId, clientType, JSONObject.toJSONString(msg));
            return;
        }
        if (StringUtils.isEmpty(msg.getReceiveUserId())) {
            log.warn("接收人不能为空: sendUserId:{} ,sendClientTYpe:{} ,msg:{}", userId, clientType, JSONObject.toJSONString(msg));
            return;
        }
        msg.setSendClientType(clientType);
        msg.setSendStartUserType(startUserType);
        msg.setSendUserId(userId);
        msg.setSendTime(LocalDateTime.now());
        saveMsg(msg);
        boolean send = true;
        if (StringUtils.isEmpty(msg.getReceiveClientType())) {
            send = StartConnectManager.getInstance().sendMsg(msg.getReceiveStartUserType(), msg.getReceiveUserId(), JSONObject.toJSONString(msg), null, true);
        } else {
            send = StartConnectManager.getInstance().sendMsg(msg.getReceiveStartUserType(), msg.getReceiveUserId(), JSONObject.toJSONString(msg), msg.getReceiveClientType(), true);
        }

    }

    @Override
    public T formatMsg(String msg) {
        Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return JSONObject.parseObject(msg, entityClass);
    }

    @Override
    public void saveMsg(T msg) {
        if (storage == null) {
            log.warn("storage is null single msg Cannot store. msg:{}", JSONObject.toJSONString(msg));
            return;
        }
        msg.setConversationType(handlerMsgType());
        storage.saveMsg(msg);
    }

    /**
     * 发送消息群
     *
     * @param msg
     */
    @Override
    public void sendMsg(T msg) {
        if (StringUtils.isEmpty(msg.getConversationId())) {
            throw new StartBusException("会话id不能为空");
        }
        if (StringUtils.isEmpty(msg.getSendUserId())) {
            throw new StartBusException("发送人不能为空");
        }
        if (StringUtils.isEmpty(msg.getReceiveUserId())) {
            throw new StartBusException("接收人不能为空");
        }
        saveMsg(msg);
        String userKey = StartConnectManager.getUserKey(msg.getReceiveStartUserType(), msg.getReceiveUserId());
        StartConnectManager.getInstance().sendMsg(userKey, JSONObject.toJSONString(msg), msg.getReceiveClientType(), true);
    }
}
